package com.lyj.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyj.pojo.LayuiPage;
import com.lyj.pojo.User;
import com.lyj.service.UserService;
import com.lyj.util.LayuiData;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(HttpSession session,HttpServletResponse response,
                        String loginName, String password,
                        String checkCode, String autoLogin) {

//        System.out.println("自动登录：" + autoLogin);
        String okCheckCode = (String) session.getAttribute("checkCode");

        if (checkCode.equals(okCheckCode)) {

            User user = userService.login(loginName, password);
            if (user != null) {
                if (user.getStatus() > 0) {
                    session.setAttribute("loginUser", user);
                    if (autoLogin != null){
                        String jsonStr = JSONUtil.toJsonStr(user);
                        try {
                            jsonStr = URLEncoder.encode(jsonStr,"UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        Cookie cookie = new Cookie("user",jsonStr);
                        cookie.setMaxAge(604800);  //7天
                        cookie.setPath("/HRM");
                        response.addCookie(cookie);
                    }
                    return "redirect:/user/toHome";
                } else {
                    session.setAttribute("info", "用户未通过审核");
                    return "redirect:/toLogin";
                }
            } else {
                session.setAttribute("info", "用户名或密码错误");
                return "redirect:/toLogin";
            }
        } else {
            session.setAttribute("info", "验证码有误");
            return "redirect:/toLogin";
        }
    }
    @RequestMapping("/toHome")
    public ModelAndView toHome(ModelAndView mv){
//        System.out.println("首页跳转页面");
        User user1 = new User();
        user1.setStatus(0);
        List<User> allUser = userService.findAllUser(user1);
        mv.addObject("count",allUser.size());
        mv.setViewName("home");
        return mv;
    }

    @RequestMapping("/register")
    public void register(User user, String checkCode, HttpServletResponse response, HttpSession session) {
        String flag = "";
        String okCheckCode = (String) session.getAttribute("checkCode");
        if (checkCode.equals(okCheckCode)) {
            User user1 = userService.findUserByLoginName(user.getLoginName());
            if (user1 != null) {
                flag = "3";
            } else {
                //注册
                userService.addUser(user);
                flag = "2";
            }
        } else {
            flag = "1";
        }
        try {
            response.getWriter().write(flag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/show.html")
    public String show() {
        return "show";
    }

    @RequestMapping("/list.html")
    public String toList() {
        return "userList";
    }

    @RequestMapping("/audit.html")
    public String toAudit() {
        return "auditUser";
    }

    @RequestMapping("/addUser.html")
    public String addUser() {
        return "addUser";
    }

    @RequestMapping("/addUser")
    public void addUser(@RequestBody User user, HttpServletResponse response) {
        String flag = "";
        User user1 = userService.findUserByLoginName(user.getLoginName());
        if (user1 != null) {
            flag = "3";
        } else {
            //注册
            userService.addUser(user);
            flag = "2";
        }
        try {
            response.getWriter().write(flag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/update.html")
    public String toUpdate(Integer id, Model model) {
        model.addAttribute("user", userService.findUserById(id));
        return "userUpdate";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session,HttpServletResponse response) {
        session.removeAttribute("loginUser");
        Cookie cookie = new Cookie("user", null);
        cookie.setPath("/HRM");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/toLogin";
    }


    @RequestMapping("/list")
    public ResponseEntity list(LayuiPage layuiPage, User user) {
        PageHelper.startPage(layuiPage.getPage(), layuiPage.getLimit());
        List<User> users = userService.findAllUser(user);
        PageInfo pageInfo = new PageInfo(users);
        return ResponseEntity.ok(LayuiData.toLayuiTableModel(pageInfo));
    }

    @RequestMapping("/auditList")
    public ResponseEntity audit(LayuiPage layuiPage, User user) {
        PageHelper.startPage(layuiPage.getPage(), layuiPage.getLimit());
        List<User> users = userService.findAllUser(user);
        PageInfo pageInfo = new PageInfo(users);
        return ResponseEntity.ok(LayuiData.toLayuiTableModel(pageInfo));
    }

    @RequestMapping("/update")
    public ResponseEntity update(@RequestBody User user) {
        List<User> allUser = userService.findAllUser(new User());
        for (User user1 : allUser) {
            if (user1.getLoginName().equals(user.getLoginName()) && user1.getId() != user.getId()){
                return ResponseEntity.ok("该登录名已经存在");
            }
        }
        userService.updateById(user);
        return ResponseEntity.ok("1");
    }

    @RequestMapping("/delete/{id}")
    public ResponseEntity delete(@PathVariable Integer id) {
        User user = userService.findUserById(id);
        if (user.getStatus() == 2) {
            return ResponseEntity.ok(new String("2"));
        } else {
            userService.deleteById(id);
        }

        return ResponseEntity.ok(new String("1"));
    }

    @RequestMapping("/audit")
    public ResponseEntity audit(Integer[] ids) {
        userService.auditUserByIds(ids);
        return ResponseEntity.ok(new String("1"));
    }

    @RequestMapping("/updatePassword")
    public ResponseEntity updatePassword(Integer id,String password,String newPassword){
        User user1 = userService.findUserById(id);
        if (!user1.getPassword().equals(password)){
            return ResponseEntity.ok("2");
        }
        if (newPassword.length()>16){
            return ResponseEntity.ok("3");
        }
        user1.setPassword(newPassword);
        userService.updatePasswordById(user1);
        return ResponseEntity.ok("1");
    }

    @RequestMapping("/updateAvatar")
    public ResponseEntity updateAvatar(Integer id,String avatar,HttpSession session){
        userService.updateAvatarById(id,avatar);
        session.setAttribute("loginUser",userService.findUserById(id));
        return ResponseEntity.ok(LayuiData.success());
    }

    @RequestMapping("toUpdateAvatar")
    public String toUpdateAvatar(){
        return "updateAvatar";
    }

    @RequestMapping("toUserMsg")
    public String toUserMsg(){
        return "userMsg";
    }

    @RequestMapping("toUpdatePassword")
    public String toUpdatePassword(){
        return "updatePassword";
    }

    @RequestMapping("/uploadAvatar")
    public ResponseEntity uploadAvatar(MultipartFile file, HttpSession session) {
        String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = "" + System.currentTimeMillis() + (new Random().nextInt(900) + 100) + type ;
        String path = session.getServletContext().getRealPath("images/avatars");
        File uploadFile = new File(path, fileName);
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.ok(LayuiData.toLayuiUploadError(1, "服务器异常，文档上传失败"));
        }
        return ResponseEntity.ok(LayuiData.toLayuiUploadSuccess(uploadFile.getAbsolutePath(),fileName));
    }


}
